<template>
  <el-upload
      class="avatar-uploader"
      :show-file-list="false"
      :action="$uploadUrl"
      :headers="uploadHeader"
      :on-success="handleUploadSuccess"
      :on-error="hideLoading"
      :before-upload="showLoading">
    <img v-if="data.url" :src="data.url" class="upload-img">
    <div v-else >
      <img src="../../assets/images/common/upload.png"/>
    </div>
  </el-upload>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
  import common from "../../utils/common";
import {getToken} from "../../utils/auth";
import {ElLoading} from "element-plus";

  const props = defineProps({
    modelValue:{
      type: String
    }
  });

  const data = reactive({
    url: null,
    showLoading: false
  })

  const uploadHeader = ref({ 'session-key': getToken() });

  onMounted(() => {
    data.url = props.modelValue
  })

  const emits = defineEmits(['update:modelValue'])

  function handleUploadSuccess(response){
    hideLoading()
    data.url = response.data.url
    emits('update:modelValue', data.url)
  }

  let loading
  function showLoading () {
    loading = ElLoading.service({
      lock: false,
      text: '',
      background: 'rgba(0, 0, 0, 0)'
    })
  }

  function hideLoading () {
    if(loading) {
      loading.close()
      loading = null
    }
  }
</script>

<style scoped>

</style>
